#include "wxline.h"

wxLine::wxLine()
{

}

wxLine::wxLine(wxPoint spos,wxPoint epos)
    : mStartPos(spos),mEndPos(epos)
{

}

wxLine::~wxLine()
{

}

void wxLine::setPosition(wxPoint spos,wxPoint epos)
{
    mStartPos = spos;
    mEndPos = epos;
}

double wxLine::GetLength() const
{
    int dx = mEndPos.x - mStartPos.x;
    int dy = mEndPos.y - mStartPos.y;
    return std::sqrt(dx * dx + dy * dy);
}

wxPoint wxLine::GetPointAtLength(double length) const
{
    // 计算线段总长度
    double totalLength = this->GetLength();
    if (totalLength == 0) return mStartPos; // 零长度线段直接返回起点

    // 约束长度在 [0, totalLength] 范围内
    length = std::max(0.0, std::min(length, totalLength));

    // 计算单位方向向量
    double ux = (mEndPos.x - mStartPos.x) / totalLength;
    double uy = (mEndPos.y - mStartPos.y) / totalLength;

    // 计算目标点
    wxPoint point;
    point.x = mStartPos.x + length * ux;
    point.y = mStartPos.y + length * uy;

    return point;
}

wxPoint wxLine::GetNormalPoint(const wxPoint& pointOnLine, double normalLength, NormalSide normalSide) const
{
    // 计算方向向量 AB
    double dx = mEndPos.x - mStartPos.x;
    double dy = mEndPos.y - mStartPos.y;

    // 计算单位方向向量
    double length = this->GetLength();
    if (length == 0) return pointOnLine; // 避免除以零

    double ux = dx / length;
    double uy = dy / length;

    // 计算法线方向
    double nx, ny;
    if (normalSide == NORMAL_LEFT) {
        nx = uy;      // 左侧法线（顺时针旋转90°）
        ny = -ux;
    } else {
        nx = -uy;      // 右侧法线（逆时针旋转90°）
        ny = ux;
    }

    // 计算法线终点
    wxPoint normalPoint;
    normalPoint.x = pointOnLine.x + normalLength * nx;
    normalPoint.y = pointOnLine.y + normalLength * ny;

    return normalPoint;
}
